import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook

def get_tables_from_url(url):
    response = requests.get(url)
    if response.status_code == 200:
        soup = BeautifulSoup(response.content, 'html.parser')
        tables = soup.find_all('table')
        return tables
    else:
        print("Failed to retrieve the webpage.")
        return None

def save_tables_to_excel(tables, filename):
    wb = Workbook()
    for index, table in enumerate(tables):
        ws = wb.create_sheet(title=f'Table_{index+1}')
        for row_index, row in enumerate(table.find_all('tr')):
            for col_index, cell in enumerate(row.find_all(['th', 'td'])):
                ws.cell(row=row_index+1, column=col_index+1, value=cell.get_text())
    del wb['Sheet']  # Deleting default sheet
    wb.save(filename)
    print(f"Tables saved to {filename}.")

if __name__ == "__main__":
    url = input("请输入要爬取的网站的URL：")
    filename = input("请输入要保存的Excel文件名：")
    tables = get_tables_from_url(url)
    if tables:
        save_tables_to_excel(tables, filename)
